package common.tool.box.quartz.task;

import common.tool.box.common.config.CommonToolBoxConfig;
import common.tool.box.common.constant.Constants;
import common.tool.box.common.utils.DateUtils;
import common.tool.box.common.utils.StringUtils;
import common.tool.box.common.utils.file.FileUploadUtils;
import common.tool.box.common.utils.file.FileUtils;
import common.tool.box.system.domain.SysUserFile;
import common.tool.box.system.service.impl.SysUserFileServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Component("anonUserFileTask")
public class AnonUserFileTask {
    private static final Logger log = LoggerFactory.getLogger(AnonUserFileTask.class);

    @Autowired
    private SysUserFileServiceImpl sysUserFileService;

    public void cleanFileEveryday(String userName, String filePath, Integer saveDay) {
        log.debug("[ScheduledTask] cleanFileEveryday start");
        // 先查出指定用户的文件
        SysUserFile sysUserFile = new SysUserFile();
        sysUserFile.setUserName(userName);
        sysUserFile.setCreateTime(DateUtils.addDayToDate(new Date(), -saveDay));
        List<SysUserFile> sysUserFileList = sysUserFileService.selectSysUserFileList(sysUserFile);
        if (sysUserFileList != null && sysUserFileList.size() > 0) {
            List<String> filePathList = new ArrayList<>();
            // 删除文件及其关联
            sysUserFileList.forEach(file -> {
                try {
                    FileUtils.deleteFile(FileUploadUtils.getAbsoluteFile(CommonToolBoxConfig.getProfile()
                            , StringUtils.substringAfter(file.getFilePath(), Constants.RESOURCE_PREFIX))
                            .getAbsolutePath());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                filePathList.add(file.getFileId());
            });
            sysUserFileService.deleteSysUserFileByFileIds(filePathList);
        }
        log.debug("[ScheduledTask] cleanFileEveryday finish, total: {}", Optional.ofNullable(sysUserFileList).map(List::size).orElse(0));
    }
}
